<template>
  <div class="parent">
    <div class="title">
      模型配置
    </div>
    <el-form ref="ruleFormRef" :rules="rules" :inline="true" :model="formInline" class="demo-form-inline">
      <ElCard class="art-table-card" shadow="never" style="margin-top: 20px">
        <el-form-item label="模型名称" prop="name">
          <el-input v-model="formInline.name" placeholder="请输入模型名称" clearable />
        </el-form-item>
        <el-form-item label="模型编号" prop="number">
          <el-input v-model="formInline.number" placeholder="输入模型编号" clearable />
        </el-form-item>
        <el-form-item label="模型标签" prop="tag">
          <el-select v-model="formInline.tag" placeholder="请选择标签" clearable>
            <el-option label="服务器" value="服务器" />
            <el-option label="短信" value="短信" />
          </el-select>
        </el-form-item>
      </ElCard>

      <ElCard class="art-table-card" shadow="never" style="margin-top: 20px">
        <el-button link type="primary" style="float: right;" @click.stop="addR()">新增测点</el-button>
        <div @click="">
          <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="attName" label="测点名称" width="180">
              <template #default="{ row, $index }">
                <el-input v-if="editingIndex === $index" v-model="row.attName" @click.stop />
                <span v-else>{{ row.attName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="attKey" label="测点key" width="180">
              <template #default="{ row, $index }">
                <el-input v-if="editingIndex === $index" v-model="row.attKey" @click.stop />
                <span v-else>{{ row.attKey }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="attType" label="测点数据类型" width="180">
              <template #default="{ row, $index }">
                <!-- '测点key的数据类型 1数值 2日期yyyy-MM-dd 3 日期yyyy-MM-dd HH:mm:ss', -->
                <el-select v-if="editingIndex === $index" v-model="row.attType" placeholder="请选择数据类型" clearable
                  @click.stop style="width: 100%;">
                  <el-option label="数值" value="1" />
                  <el-option label="日期yyyy-MM-dd" value="2" />
                  <el-option label="日期yyyy-MM-dd HH:mm:ss" value="3" />
                </el-select>
                <el-select :disabled="true" v-else v-model="row.attType" placeholder="请选择数据类型" clearable @click.stop
                  style="width: 100%;">
                  <el-option label="数值" value="1" />
                  <el-option label="日期yyyy-MM-dd" value="2" />
                  <el-option label="日期yyyy-MM-dd HH:mm:ss" value="3" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="remakes" label="测点备注">
              <template #default="{ row, $index }">
                <el-input v-if="editingIndex === $index" v-model="row.remakes" @click.stop />
                <span v-else>{{ row.remakes }}</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="120">
              <template #default="{ row, $index }">
                <el-button link type="primary" size="small" @click.stop="handleDelete($index)">
                  删除
                </el-button>
                <el-button v-if="editingIndex === $index" link type="primary" size="small" @click.stop="handleSave">
                  保存
                </el-button>
                <el-button v-else link type="primary" size="small" @click.stop="handleEdit($index)">
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </ElCard>
      <ElCard class="art-table-card" shadow="never" style="">
        <div style="float: right;">
          <el-button type="primary" @click="importBoxDialogVisible = true">导入</el-button>
          <el-button type="primary" @click="exportData()">导出</el-button>
          <el-button type="primary" @click="onSubmit(ruleFormRef)">保存</el-button>
        </div>
      </ElCard>
    </el-form>

    <el-dialog v-model="importBoxDialogVisible" title="导入" width="500" :before-close="handleImportBoxClose">
      <el-input :rows="8" v-model="importData" type="textarea" placeholder="请粘贴模版数据" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importBoxDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleImportData()">
            确认导入
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { reactive } from 'vue'
import { BmslzService } from '@/api/bmslzApi'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import useClipboard from 'vue-clipboard3';
import { useRouter } from 'vue-router';
const router = useRouter();
const route = useRoute();
const modelId = route.query.id as string;
const importData = ref('')
const { toClipboard } = useClipboard()

// 定义类型接口
interface AttPoint {
  attName: string;
  attKey: string;
  attType: string;
  remakes?: string;
}


const importBoxDialogVisible = ref(false)

const handleImportBoxClose = (done: () => void) => {
  done()
}

onMounted(async () => {
  //如果传入id说明是修改 否则就是新增
  const modelId = route.query.id as string;
  //清空数据
  formInline.name = ''
  formInline.number = ''
  formInline.tag = ''
  formInline.att = ''
  tableData.value = [];
  if (!modelId) {
    return;
  }
  try {
    //查询模板详情
    const data = await BmslzService.monitorModelQueryById({
      id: modelId,
    })
    if (!data) {
      ElMessage.error('模型不存在');
      router.go(-1); // -1 表示返回上一页
    }

    //表单基础数据回显
    formInline.name = data.name;
    formInline.number = data.number
    formInline.tag = data.tag
    const parsedData: AttPoint[] = JSON.parse(data.att)
    //att数据回显
    tableData.value = parsedData
  } catch (err) {
  } finally {
  }
});
const ruleFormRef = ref<FormInstance>()
interface RuleForm {
  name: string
  number: string
  tag: string
}
const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '模型名称不能为空', trigger: 'blur' },
    { min: 1, max: 50, message: '模型名称要在50个字符内', trigger: 'blur' },
  ],
  number: [
    { required: true, message: '模型编号不能为空', trigger: 'blur' },
    { min: 1, max: 50, message: '模型编号要在50个字符内', trigger: 'blur' },],
  tag: [
    { required: true, message: '标签不能为空', trigger: 'blur' }],
})


const tableData = ref<AttPoint[]>([]);
const editingIndex = ref(-1);
const originalData = ref({});

// 删除行
const handleDelete = (index: any) => {
  tableData.value.splice(index, 1);
};

// 新增行
const addR = () => {
  tableData.value.push({
    attName: '',
    attKey: '',
    attType: '1',//'测点key的数据类型 1数值 2日期yyyy-MM-dd 3 日期yyyy-MM-dd HH:mm:ss',
    remakes: ''
  },)
};
// 编辑行
const handleEdit = (index: any) => {
  // 保存原始数据以便取消编辑
  originalData.value = { ...tableData.value[index] };
  editingIndex.value = index;
};

// 保存编辑
const handleSave = () => {
  editingIndex.value = -1;
  originalData.value = {};
};

// 点击行外保存
const handleClickOutside = () => {
  if (editingIndex.value !== -1) {
    handleSave();
  }
};

// 如果需要取消编辑功能，可以添加：
// const handleCancel = () => {
//   if (editingIndex.value !== -1) {
//     tableData.value[editingIndex.value] = { ...originalData.value };
//     editingIndex.value = -1;
//   }
// };

const formInline = reactive({
  name: '',
  number: '',
  tag: '',
  att: ''
})


const handleImportData = () => {
  try {
    let data = JSON.parse(importData.value)
    formInline.name = data.formInline.name;
    formInline.number = data.formInline.number;
    formInline.tag = data.formInline.tag;
    formInline.att = data.formInline.att;
    tableData.value = data.tableData;
    importBoxDialogVisible.value = false
  } catch (err) {
    ElMessage.error('内容错误,请检查模版格式是否正确');
  } finally {
  }

};

const exportData = () => {
  let exportData = ref<any>();
  exportData.value = {
    "formInline": formInline,
    "tableData": tableData
  }

  try {
    debugger
    toClipboard(JSON.stringify(exportData.value))
    ElMessage.success('模板内容已经导出到剪贴板');
  } catch (err) {
    console.error("复制失败", err);
    ElMessage.error('复制失败');
  }
};

const onSubmit = async (formEl: FormInstance | undefined) => {
  let returnT = ref<boolean>(false);
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (!valid) {
      ElMessage.error('数据填写不完整');
      returnT.value = true
    }
  })

  for (const item of tableData.value) {
    if (!item.attName || !item.attType || !item.attKey) {
      ElMessage.error('测点数据填写不完整');
      returnT.value = true;
      break; // ✅ 直接退出循环
    }
  }
  if (returnT.value) {
    return;
  }
  console.log('submit!')
  if (!modelId) {
    //新增模型
    const { name } = await BmslzService.monitorModelAdd({
      name: formInline.name,
      number: formInline.number,
      tag: formInline.tag,
      att: JSON.stringify(tableData.value)
    })
  } else {
    //修改模型
    const { name } = await BmslzService.monitorModelEdit({
      id: modelId,
      name: formInline.name,
      number: formInline.number,
      tag: formInline.tag,
      att: tableData.value.length > 0 ? JSON.stringify(tableData.value) : null
    })
  }
  ElMessage.success('操作成功！');
  router.go(-1); // -1 表示返回上一页
}

</script>

<style lang="scss" scoped>
.el-input {
  width: 100%;
}

.parent {
  padding: 0 0 0 20px;

  .title {
    color: #101010;
    font-size: 20px;
    font-weight: bold;
  }
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
